<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref, reactive } from 'vue';

import { Page, useVbenDrawer, VbenCountToAnimator } from '@vben/common-ui';

import { Button, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteRentBill, queryRentBillList, queryRentTotal } from '#/api';

import ExtraDrawer from './Drawer.vue';

const tTime = (time) => dayjs(time).format('YYYY-MM');

interface RowType {
  category: string;
  color: string;
  id: string;
  price: string;
  productName: string;
  releaseDate: string;
}

const formOptions: VbenFormProps = {
  // 默认展开
  schema: [
    {
      component: 'DatePicker',
      fieldName: 'date',
      componentProps: {
        picker: 'month',
        placeholder: '请选择月份',
        valueFormat: 'YYYY-MM',
      },
      label: '月份',
    },
    {
      component: 'Select',
      fieldName: 'settle_utilities',
      componentProps: {
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
      },
      label: '结算水电',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};
const pageTotal = ref(0);
const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { title: '月份', field: 'month', slots: { default: 'month' }, width: 100 },
    { title: '当前水表读数', field: 'water_current', width: 150 },
    { title: '当前电表读数', field: 'electric_current', width: 150 },
    { title: '上月水表读数', field: 'water_last', width: 150 },
    { title: '上月电表读数', field: 'electric_last', width: 150 },
    { title: '用水量（吨）', field: 'water_usage', width: 100 },
    { title: '用电量（度）', field: 'electric_usage', width: 100 },
    { title: '水费', field: 'water_fee', width: 100 },
    { title: '电费', field: 'electric_fee', width: 100 },
    { title: '房租', field: 'rent', width: 100 },
    { title: '卫生费', field: 'clean_fee', width: 100 },
    {
      title: '结算水电',
      field: 'settle_utilities',
      slots: { default: 'settle' },
    },
    { title: '总金额', field: 'total', width: 100 },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 100,
    },
  ],
  pagerConfig: {
    pageSize: 10,
  },
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const data = await queryRentBillList({
          page: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        pageTotal.value = data.total;
        reloadRentCount();
        return data;
      },
    },
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
function deleteRentBillRow(id) {
  deleteRentBill(id).then(() => {
    gridApi.reload();
    reloadRentCount();
  });
}

const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
  onOpenChange(isOpen) {
    if (!isOpen) {
      gridApi.reload();
      reloadRentCount();
    }
  },
});

const rentCount = reactive({
  total_electric_usage: 0,
  total_water_usage: 0,
  total_electric_fee: 0,
  total_water_fee: 0,
  total_rent: 0,
  total_amount: 0,
});

function reloadRentCount() {
  queryRentTotal().then((r) => {
    Object.assign(rentCount, r);
  });
}
</script>

<template>
  <div>
    <div class="stats-container bg-background text-foreground">
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-label">电费(￥)</div>
          <div class="stat-value">
            <VbenCountToAnimator
              :duration="200"
              :end-val="Number(rentCount.total_electric_fee)"
              :start-val="0"
            />
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-label">水费(￥)</div>
          <div class="stat-value">
            <VbenCountToAnimator
              :duration="200"
              :end-val="Number(rentCount.total_water_fee)"
              :start-val="0"
            />
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-label">用电量(度)</div>
          <div class="stat-value">
            <VbenCountToAnimator
              :duration="200"
              :end-val="Number(rentCount.total_electric_usage)"
              :start-val="0"
            />
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-label">用水量(吨)</div>
          <div class="stat-value">
            <VbenCountToAnimator
              :duration="200"
              :end-val="Number(rentCount.total_water_usage)"
              :start-val="0"
            />
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-label">房租(￥)</div>
          <div class="stat-value">
            <VbenCountToAnimator
              :duration="200"
              :end-val="Number(rentCount.total_rent)"
              :start-val="0"
            />
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-label">总计(￥)</div>
          <div class="stat-value">
            <VbenCountToAnimator
              :duration="200"
              :end-val="Number(rentCount.total_amount)"
              :start-val="0"
            />
          </div>
        </div>
      </div>
    </div>
    <Page>
      <div class="vp-raw w-full">
        <Grid>
          <template #toolbar-tools>
            <Button class="mr-2" type="primary" @click="drawerApi.open()">
              新增
            </Button>
          </template>
          <template #action="{ row }">
            <Button
              danger
              type="link"
              @click="deleteRentBillRow(row.id)"
              :disabled="row.rank !== pageTotal"
            >
              删除
            </Button>
          </template>
          <template #month="{ row }">
            <Button type="link">{{ tTime(row.month) }}</Button>
          </template>
          <template #settle="{ row }">
            <Tag color="green" v-if="row.settle_utilities === 1">是</Tag>
            <Tag color="red" v-else>否</Tag>
          </template>
        </Grid>
      </div>
      <Drawer />
    </Page>
  </div>
</template>
<style scoped>
.stats-container {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 20px 20px 0 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
  justify-content: center;
}

.stat-item {
  text-align: center;
  padding: 16px;
  border-radius: 6px;
  transition: transform 0.2s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  font-weight: 500;
}

.stat-value {
  font-size: 28px;
  margin-bottom: 8px;
}

.status-indicator {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-running .status-indicator {
  background-color: #1890ff; /* 蓝色 - 进行中 */
}

.status-success .status-indicator {
  background-color: #52c41a; /* 绿色 - 成功 */
}

.status-failure .status-indicator {
  background-color: #ff4d4f; /* 红色 - 失败 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 16px;
  }

  .stat-value {
    font-size: 24px;
  }

  .stat-label {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .stat-item {
    padding: 12px;
  }

  .stat-value {
    font-size: 20px;
  }
}
</style>
